package com.hrt.datasender.datacollect;

import java.util.ArrayList;
import java.util.List;

import org.quartz.JobExecutionContext;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import com.btcode.schedule.ScheduleManager;
import com.btcode.schedule.SingleInstanceJob;
import com.hrt.datasender.datacollect.drive.DriveLoader;
import com.hrt.datasender.datacollect.drive.IDrive;
import com.hrt.datasender.datadao.model.BdSourceModel;
import com.hrt.datasender.datadao.service.BdSourceService;
import com.hrt.datasender.datadao.service.BdSourceSingleService;

/**
 * 定时获取数据
 *
 * @author gislin
 */
public class DataGetter extends SingleInstanceJob {

    private ILog log;
    private ILog dataLog;

    @Override
    public void initJob(JobExecutionContext arg0) {
        log = MyLog.getInstance().getLogger(DataGetter.class);
        dataLog = MyLog.getInstance().getLogger("BD_SOURCE_RECORD");
    }

    @Override
    public void myExecute(JobExecutionContext arg0) {

        try {

            log.info("开始从设备获取数据");

            List<BdSourceModel> modelsAll = new ArrayList<>();

            List<IDrive> drives = DriveLoader.getInstance().loadAndGetDrive();

            for (IDrive drive : drives) {
                if (drive == null) {
                    continue;
                }
                List<BdSourceModel> models = drive.getCurrentData();
                if (models != null) {
                    modelsAll.addAll(models);
                }
            }

            if (modelsAll.size() > 0) {
                log.info("获取数据成功，数量：" + modelsAll.size());
            }
            else {
                log.info("暂无数据");
            }

            //将数据记录到文档文件上，必须放在数据库操作之前
            for (BdSourceModel bdSourceModel : modelsAll) {
                dataLog.info(bdSourceModel);
            }

            // 单位转换
            modelsAll = BdSourceService.getInstance().unitConver(modelsAll);

            //量程转换
            modelsAll = BdSourceService.getInstance().rangeConver(modelsAll);

            BdSourceService.getInstance().add(modelsAll);
            BdSourceSingleService.getInstance().update(modelsAll);
        }
        catch (Exception e) {
            log.error("从设备获取数据失败", e);
        }

    }

    public static void init() {
        ILog log = MyLog.getInstance().getLogger(DataGetter.class);

        try {

            log.info("开始初始化数据获取器");

            DriveLoader.getInstance().loadAndGetDrive();

            log.info("初始化数据获取器成功");

        }
        catch (Exception e) {
            log.error("初始化数据获取器出错", e);
        }
        ScheduleManager.getInstance().addJob(DataGetter.class, "0/15 * * * * ?");
    }

}
